package com.jilian.mydemo.modul.order.ui;

import android.app.Dialog;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.route.BikingRoutePlanOption;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.jilian.mydemo.R;
import com.jilian.mydemo.base.BaseDto;
import com.jilian.mydemo.base.BaseFragment;
import com.jilian.mydemo.common.dto.OrderDetailDto;
import com.jilian.mydemo.common.dto.OrderDto;
import com.jilian.mydemo.common.dto.OrderListDto;
import com.jilian.mydemo.common.dto.PlanPathListDto;
import com.jilian.mydemo.listener.CustomItemClickListener;
import com.jilian.mydemo.modul.order.adapter.ThreeOrderAdapter;
import com.jilian.mydemo.modul.order.viewmodel.OrderViewModel;
import com.jilian.mydemo.utils.DisplayUtil;
import com.jilian.mydemo.utils.EmptyUtils;
import com.jilian.mydemo.utils.PinziDialogUtils;
import com.jilian.mydemo.utils.ToastUitl;
import com.jilian.mydemo.utils.overlayutil.MyBikingRouteOverlay;
import com.jilian.mydemo.views.RecyclerViewSpacesItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ThreeOrderFragment extends BaseFragment implements CustomItemClickListener, ThreeOrderAdapter.ThreeOrderListener {
    private MapView mapView;
    private RecyclerView recyclerview;
    private ThreeOrderAdapter adapter;
    private LinearLayoutManager linearLayoutManager;
    private List<OrderDto> datas;
    private SmartRefreshLayout srHasData;
    private SmartRefreshLayout srNoData;
    private BaiduMap baiduMap;

    @Override
    protected void loadData() {
        showLoadingDialog();
        pageNum = 1;
        queryOrderList();
        getMapData();
    }

    private Integer pageNum = 1;
    private Integer pageSize = 20;


    /**
     * 获取订单列表
     */
    private void queryOrderList() {
        orderViewModel.queryOrderList(pageNum, pageSize, 4, queryKey);
        orderViewModel.getOrderliveData().observe(this, new Observer<BaseDto<OrderListDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<OrderListDto> dto) {
                hideLoadingDialog();
                srNoData.finishRefresh();
                srHasData.finishRefresh();
                srHasData.finishLoadMore();
                //有数据
                if (dto.isSuccess() && EmptyUtils.isNotEmpty(dto.getData().getList())) {
                    srNoData.setVisibility(View.GONE);
                    srHasData.setVisibility(View.VISIBLE);
                    mapView.setVisibility(View.VISIBLE);
                    if (pageNum == 1) {
                        datas.clear();
                    }
                    datas.addAll(dto.getData().getList());
                    adapter.notifyDataSetChanged();
                } else {
                    //说明是上拉加载
                    if (pageNum > 1) {
                        pageNum--;
                    } else {
                        //第一次就没数据
                        srNoData.setVisibility(View.VISIBLE);
                        srHasData.setVisibility(View.GONE);
                        mapView.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    private OrderViewModel orderViewModel;

    @Override
    protected void createViewModel() {
        orderViewModel = ViewModelProviders.of(this).get(OrderViewModel.class);
    }

    List<LatLng> mPointList;

    /**
     * 获取工单地图
     */
    private void getMapData() {
        orderViewModel.planPath();
        orderViewModel.getPlanPathliveData().observe(this, new Observer<BaseDto<PlanPathListDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<PlanPathListDto> dtoBaseDto) {
                hideLoadingDialog();
                //清除地图的数据
                baiduMap.clear();
                if (dtoBaseDto.isSuccess()) {
                    if (EmptyUtils.isNotEmpty(dtoBaseDto.getData()) && EmptyUtils.isNotEmpty(dtoBaseDto.getData().getList())) {
                        mPointList = new ArrayList<>();
                        for (int i = 0; i < dtoBaseDto.getData().getList().size(); i++) {
                            String latStr = dtoBaseDto.getData().getList().get(i).getLocation().split(",")[0];
                            Double lat = Double.parseDouble(latStr);
                            String lonStr = dtoBaseDto.getData().getList().get(i).getLocation().split(",")[1];
                            Double lon = Double.parseDouble(lonStr);
                            LatLng latLng = new LatLng(lat, lon);
                            mPointList.add(latLng);
                            if (i == 0) {
                                initMapLocation(lat, lon);
                            }
                        }
                        //只有一个点
                        if(EmptyUtils.isNotEmpty(mPointList)&&mPointList.size()==1){
                            showPointsInBaiduMap(mPointList,null);
                        }
                        else{

                            showLinesInBaiduMap(mPointList);
                        }


                    }
                } else {
                    ToastUitl.showImageToastTips(dtoBaseDto.getMsg());
                }
            }
        });
    }

    /**
     * 画线
     *
     * @param mPointList
     */
    private void showLinesInBaiduMap(List<LatLng> mPointList) {
        if (EmptyUtils.isNotEmpty(mPointList) && mPointList.size() > 1) {

            for (int i = mPointList.size() - 1; i >= 1; i--) {

                PlanNode stNode = PlanNode.withLocation(mPointList.get(i));
                PlanNode enNode = PlanNode.withLocation(mPointList.get(i - 1));

                mSearch.bikingSearch((new BikingRoutePlanOption())
                        .from(stNode)
                        .to(enNode)
                        // ridingType  0 普通骑行
                        //            1 电动车骑行
                        // 默认普通骑行
                        .ridingType(1));
            }
        }


    }

    /**
     * 定位到某个坐标点
     *
     * @param latitude
     * @param longitude
     */
    private void initMapLocation(double latitude, double longitude) {
        // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        // 构造定位数据
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(200)
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(100).latitude(latitude)
                .longitude(longitude).build();
        // 设置定位数据
        baiduMap.setMyLocationData(locData);
        // 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）
        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
                .fromResource(R.drawable.image_now_adress);
        MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, mCurrentMarker);
        baiduMap.setMyLocationConfiguration(config);
        // 当不需要定位图层时关闭定位图层
        baiduMap.setMyLocationEnabled(false);

    }

    /**
     * 在地图上展示各个点
     *
     * @param pointList
     */
    private void showPointsInBaiduMap(List<LatLng> pointList, Integer resours) {

        if (resours == null) {
            //创建OverlayOptions的集合
            List<OverlayOptions> options = new ArrayList<>();
            for (int i = 0; i < pointList.size(); i++) {
                //构建MarkerOption，用于在地图上添加Marker
                MarkerOptions option = new MarkerOptions();
                option.position(pointList.get(i));
                //构建Marker图标
                option.icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.image_location_target));
                //在地图上添加Marker，并显示
                options.add(option);
                //定义文字所显示的坐标点
            }
            //在地图上批量添加
            baiduMap.addOverlays(options);
        } else {
            //创建OverlayOptions的集合
            List<OverlayOptions> options = new ArrayList<>();
            //构建MarkerOption，用于在地图上添加Marker
            MarkerOptions option = new MarkerOptions();
            option.position(pointList.get(0));
            option.icon(BitmapDescriptorFactory
                    .fromResource(resours));
            //在地图上添加Marker，并显示
            options.add(option);
            //定义文字所显示的坐标点
            //在地图上批量添加
            baiduMap.addOverlays(options);
        }

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_threeorder;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        mapView = (MapView) view.findViewById(R.id.mapView);
        recyclerview = (RecyclerView) view.findViewById(R.id.recyclerview);
        srHasData = (SmartRefreshLayout) view.findViewById(R.id.sr_has_data);
        srNoData = (SmartRefreshLayout) view.findViewById(R.id.sr_no_data);
        srHasData.setVisibility(View.GONE);
        srNoData.setVisibility(View.VISIBLE);
        srNoData.setEnableLoadMore(false);
        linearLayoutManager = new LinearLayoutManager(getParentFragment().getActivity());
        recyclerview.setLayoutManager(linearLayoutManager);
        datas = new ArrayList<>();
        HashMap<String, Integer> map = new HashMap<>();
        map.put(RecyclerViewSpacesItemDecoration.BOTTOM_DECORATION, DisplayUtil.dip2px(getParentFragment().getActivity(), 10));//下间距
        recyclerview.addItemDecoration(new RecyclerViewSpacesItemDecoration(map));
        adapter = new ThreeOrderAdapter(getParentFragment().getActivity(), datas, this, this);
        recyclerview.setAdapter(adapter);
        mapView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getParentFragment().getActivity(), MapViewActivity.class));
            }
        });
        baiduMap = mapView.getMap();
    }

    private RoutePlanSearch mSearch;

    @Override
    protected void initData() {
        mSearch = RoutePlanSearch.newInstance();
    }

    @Override
    protected void initListener() {
        OnGetRoutePlanResultListener listener = new OnGetRoutePlanResultListener() {
            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

            }

            @Override
            public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

            }

            @Override
            public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

            }

            @Override
            public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {

            }

            @Override
            public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

            }

            @Override
            public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {
                //创建BikingRouteOverlay实例
                MyBikingRouteOverlay overlay = new MyBikingRouteOverlay(baiduMap);
                if (EmptyUtils.isNotEmpty(bikingRouteResult.getRouteLines())) {
                    //获取路径规划数据,(以返回的第一条路线为例）
                    //为BikingRouteOverlay实例设置数据
                    overlay.setData(bikingRouteResult.getRouteLines().get(0));
                    //在地图上绘制BikingRouteOverlay
                    overlay.addToMap();
                } else {
                    showPointsInBaiduMap(mPointList, null);
                }
            }
        };
        mSearch.setOnGetRoutePlanResultListener(listener);
        srHasData.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNum = 1;
                queryOrderList();
                getMapData();
            }
        });
        srHasData.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNum++;
                queryOrderList();
            }
        });
        srNoData.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNum = 1;
                queryOrderList();
                getMapData();
            }
        });
    }

    @Override
    public void onItemClick(View view, int position) {
        Integer status = datas.get(position).getStatus();
        if (status != null) {
            // 4 進行中 5 進行中（填寫完成） 6 （進行中 待支付）
            if (status == 4) {
                Intent intent = new Intent(getParentFragment().getActivity(), ThreeOrderDetailActivity.class);
                intent.putExtra("order", datas.get(position));
                intent.putExtra("orderId", datas.get(position).getId());
                startActivity(intent);
            }
            // 5 進行中（填寫完成）  待提交
            if (status == 5) {
                Intent intent = new Intent(getParentFragment().getActivity(), ThreeOrderDetaiCommitelActivity.class);
                intent.putExtra("order", datas.get(position));
                intent.putExtra("orderId", datas.get(position).getId());
                startActivity(intent);
            }
            //6、待支付
            if (status == 6) {
                Intent intent = new Intent(getParentFragment().getActivity(), ThreeOrderDetaiPayActivity.class);
                intent.putExtra("order", datas.get(position));
                intent.putExtra("orderId", datas.get(position).getId());
                startActivity(intent);

            }

        }


    }

    /**
     * 延时提醒
     *
     * @param position
     */
    @Override
    public void clickOne(int position) {
        if (!("1".equals(datas.get(position).getIsLeader())) && "1".equals(datas.get(position).getIsMore())) {
            ToastUitl.showImageToastTips("只有队长可以操作");
            return;
        }
        showOneTipsDialog(position);
    }

    /**
     * 查看服务进程
     *
     * @param position
     */
    @Override
    public void clickTwo(int position) {
        Intent intent = new Intent(getParentFragment().getActivity(), SeeServiceActivity.class);
        intent.putExtra("order", datas.get(position));
        startActivity(intent);
    }

    /**
     * 上门签到
     *
     * @param position
     */
    @Override
    public void clickThree(int position) {
        if (!("1".equals(datas.get(position).getIsLeader())) && "1".equals(datas.get(position).getIsMore())) {
            ToastUitl.showImageToastTips("只有队长可以操作");
            return;
        }
        Intent intent = new Intent(getParentFragment().getActivity(), SingUpActivity.class);
        intent.putExtra("order", datas.get(position));
        startActivity(intent);


    }

    @Override
    public void clickFour(int position) {
        showLoadingDialog();
        orderViewModel.queryDetail(datas.get(position).getId());
        orderViewModel.getDetailliveData().observe(this, new Observer<BaseDto<OrderDetailDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<OrderDetailDto> dto) {
                hideLoadingDialog();

                if (dto.isSuccess() && EmptyUtils.isNotEmpty(dto)) {
                    initDetail(dto.getData(), datas.get(position));
                } else {
                    ToastUitl.showImageToastTips(dto.getMsg());
                }

            }
        });


    }

    /**
     * 通过查询 订单详情之后再去调转
     *
     * @param orderDetailDto
     * @param orderDto
     */
    private void initDetail(OrderDetailDto orderDetailDto, OrderDto orderDto) {

        Integer status = orderDto.getStatus();
        if (status != null) {
            // 4 進行中 5 進行中（填寫完成） 6 （進行中 待支付）
            if (status == 4) {
                if (!("1".equals(orderDetailDto.getIsLeader())) && "1".equals(orderDetailDto.getIsMore())) {
                    ToastUitl.showImageToastTips("只有队长可以操作");
                    return;
                }
                //完成订单
                finishOrder(orderDto,orderDetailDto);

            }
            // 5 進行中（填寫完成）  待提交
            else if (status == 5) {
                if (!("1".equals(orderDetailDto.getIsLeader())) && "1".equals(orderDetailDto.getIsMore())) {
                    ToastUitl.showImageToastTips("只有队长可以操作");
                    return;
                }
                //提交订单
                commite(orderDto, orderDetailDto);

            }
            //6、待支付
            else if (status == 6) {
                if (!("1".equals(orderDetailDto.getIsLeader())) && "1".equals(orderDetailDto.getIsMore())) {
                    ToastUitl.showImageToastTips("只有队长可以操作");
                    return;
                }
                //支付订单
                pay(orderDto, orderDetailDto);

            }

        }


    }

    /**
     * 完成订单
     *
     * @param orderDto
     * @param orderDetailDto
     */
    private void finishOrder(OrderDto orderDto, OrderDetailDto orderDetailDto) {
        showLoadingDialog();
        orderViewModel.checkSign(orderDto.getId());
        orderViewModel.getCheckSignliveData().observe(ThreeOrderFragment.this, new Observer<BaseDto<String>>() {
            @Override
            public void onChanged(@Nullable BaseDto<String> stringBaseDto) {
                hideLoadingDialog();
                if (stringBaseDto.isSuccess()) {
                    if ("1".equals(stringBaseDto.getData())) {
                        Intent intent = new Intent(getmActivity(), FinishOrderActivity.class);
                        intent.putExtra("orderDetailDto", orderDetailDto);
                        intent.putExtra("order", orderDto);
                        intent.putExtra("orderId", orderDto.getId());
                        startActivity(intent);
                    } else {
                        ToastUitl.showImageToastTips("请先签到");
                    }
                } else {
                    ToastUitl.showImageToastTips(stringBaseDto.getMsg());
                }
            }
        });

    }

    /**
     * 支付订单
     *
     * @param orderDto
     * @param orderDetailDto
     */
    private void pay(OrderDto orderDto, OrderDetailDto orderDetailDto) {
        Intent intent = new Intent(getmActivity(), PayOrderActivity.class);
        intent.putExtra("orderDto", orderDto);
        intent.putExtra("orderId", orderDto.getId());
        intent.putExtra("dataTime", orderDetailDto.getCommitTime());
        intent.putExtra("totalMoney", (orderDetailDto.getTotalMoney() == null ? "0.00" : orderDetailDto.getTotalMoney().setScale(2, BigDecimal.ROUND_DOWN).toString()));
        startActivity(intent);

    }

    /**
     * 提交订单
     *
     * @param orderDto
     * @param orderDetailDto
     */
    private void commite(OrderDto orderDto, OrderDetailDto orderDetailDto) {
        showLoadingDialog();
        orderViewModel.commitOrder(orderDto.getId());
        orderViewModel.getCommitliveData().observe(this, new Observer<BaseDto<Long>>() {
            @Override
            public void onChanged(@Nullable BaseDto<Long> dto) {
                hideLoadingDialog();
                if (dto.isSuccess()) {
                    Intent intent = new Intent(getmActivity(), PayOrderActivity.class);
                    intent.putExtra("orderDto", orderDto);
                    intent.putExtra("orderId", orderDto.getId());
                    intent.putExtra("dataTime", dto.getData());
                    intent.putExtra("totalMoney", (orderDetailDto.getTotalMoney() == null ? "0.00" : orderDetailDto.getTotalMoney().setScale(2, BigDecimal.ROUND_DOWN).toString()));
                    startActivity(intent);
                } else {
                    ToastUitl.showImageToastTips(dto.getMsg());
                }
            }
        });
    }

    private void showOneTipsDialog(int position) {

        Dialog dialog = PinziDialogUtils.getDialogNotTouchOutside(getParentFragment().getActivity(), R.layout.dialog_confirm);
        TextView tvTitle = (TextView) dialog.findViewById(R.id.tv_title);
        TextView tvContent = (TextView) dialog.findViewById(R.id.tv_content);
        tvTitle.setText("延时提醒");
        tvContent.setText("即将发送短信提示下一个客户可能\n" +
                "会有延迟，确认发送吗？");
        TextView tvNo = (TextView) dialog.findViewById(R.id.tv_no);
        TextView tvOk = (TextView) dialog.findViewById(R.id.tv_ok);

        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                delayNotice(position);
            }
        });
        tvNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();

    }

    /**
     * 延时提醒
     *
     * @param position
     */
    private void delayNotice(int position) {
        showLoadingDialog();
        orderViewModel.delayNotice(datas.get(position).getId());
        orderViewModel.getDelayNoticeliveData().observe(this, new Observer<BaseDto>() {
            @Override
            public void onChanged(@Nullable BaseDto dto) {
                hideLoadingDialog();
                if (dto.isSuccess()) {
                    ToastUitl.showImageToastSuccess("提醒成功");
                } else {
                    ToastUitl.showImageToastTips(dto.getMsg());
                }
            }
        });
    }
}
